package com.zx.BookSeaReader.ui.local;

import android.os.Bundle;

import com.zx.BookSeaReader.R;
import com.zx.BookSeaReader.util.media.MediaStoreHelper;
import com.zx.BookSeaReader.widget.RefreshLayout;
import com.zx.BookSeaReader.widget.itemdecoration.DividerItemDecoration;
import com.zx.BookSeaReader.greendao.service.BookService;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;

/**

 * 本地书籍
 */

public class LocalBookFragment extends BaseFileFragment{
    private RefreshLayout mRlRefresh;
    private RecyclerView mRvContent;


    private BookService mBookService;
    @Override
    protected int getContentId() {
        return R.layout.fragment_local_book;
    }

    @Override
    protected void initView() {
        super.initView();
        mRlRefresh=root.findViewById(R.id.refresh_layout);
        mRvContent=root.findViewById(R.id.local_book_rv_content);
    }

    @Override
    protected void initWidget(Bundle savedInstanceState) {
        super.initWidget(savedInstanceState);
        mBookService=new BookService();
        setUpAdapter();
    }

    private void setUpAdapter(){
        mAdapter = new FileSystemAdapter();
        mRvContent.setLayoutManager(new LinearLayoutManager(getContext()));
        mRvContent.addItemDecoration(new DividerItemDecoration(getContext()));
        mRvContent.setAdapter(mAdapter);
    }

    @Override
    protected void initClick() {
        super.initClick();
        mAdapter.setOnItemClickListener(
                (view, pos) -> {
                    //如果是已加载的文件，则点击事件无效。
                    String id = mAdapter.getItem(pos).getAbsolutePath();
                    if (mBookService.existBook(id)){
                        return;
                    }

                    //点击选中
                    mAdapter.setCheckedItem(pos);

                    //反馈
                    if (mListener != null){
                        mListener.onItemCheckedChange(mAdapter.getItemIsChecked(pos));
                    }
                }
        );
    }

    @Override
    protected void processLogic() {
        super.processLogic();
        MediaStoreHelper.getAllBookFile(getActivity(),
                (files) -> {
                    if (files.isEmpty()){
                        mRlRefresh.showEmpty();
                    }
                    else {
                        mAdapter.refreshItems(files);
                        mRlRefresh.showFinish();
                        //反馈
                        if (mListener != null){
                            mListener.onCategoryChanged();
                        }
                    }
                });
    }
}
